package com.tripspins.app.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.tripspins.app.R;
import com.tripspins.app.bo.Attachment;
import com.tripspins.app.bo.Pin;
import com.tripspins.app.bo.Trip;
import com.tripspins.app.bo.User;
import com.tripspins.app.dao.AttachmentDAO;
import com.tripspins.app.dao.TripDAO;
import com.tripspins.app.dao.UserDAO;
import com.tripspins.app.helper.DbHelper;
import com.tripspins.app.helper.SyncHelper;

import java.io.File;

/**
 * Created by João.Rutkoski on 09/04/14.
 */
public class BackgroundSyncService extends Service {

    SharedPreferences settings;
    IBinder mBinder;
    DbHelper dbHelper;
    SQLiteDatabase database ;
    TripDAO tripDAO;
    UserDAO userDAO;
    User loggedUser;

    public BackgroundSyncService ()
    {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        dbHelper = new DbHelper(getApplicationContext());
        database = dbHelper.getReadableDatabase();
        userDAO = new UserDAO(database);
        loggedUser = userDAO.getLoggedUser();
        boolean syncOnlyOnWiFi = settings.getBoolean("pref_key_sync_wifi",true);
        boolean syncNow = false;
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo infoWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        boolean networkConnected = connManager.getActiveNetworkInfo().isConnected();
        if(syncOnlyOnWiFi)
        {
            if (infoWifi.isConnected()) {
                syncNow = true;
            }
        }
        else
        {
            if(networkConnected || infoWifi.isConnected())
            {
                syncNow = true;
            }
        }

        if (loggedUser != null) {
            if (syncNow) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            tripDAO = new TripDAO(database);
                            for (Trip trip : tripDAO.getTripsToSync(loggedUser.getId())) {
                                SyncHelper syncHelper = new SyncHelper();
                                syncHelper.sync(trip, getApplicationContext(), loggedUser);
                            }

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        try {
                            AttachmentDAO attachmentDAO = new AttachmentDAO(database);
                            for(Trip trip : tripDAO.getTripsSynced(loggedUser.getId()))
                            {
                                for (Pin p : trip.getPins())
                                {
                                    for (Attachment attachment : attachmentDAO.getAttachmentsToSyncByPinId(loggedUser.getId())) {
                                        File fileToSync = new File(attachment.getPath());
                                        SyncHelper syncHelper = new SyncHelper();
                                        syncHelper.sync(trip.getIdOnServer()
                                                , p.getId()
                                                , attachment.getId()
                                                , fileToSync
                                                , getApplicationContext()
                                                ,loggedUser
                                        );
                                    }
                                }
                            }



                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        database.close();

                    }
                }).start();
            }
        }else {
            Toast.makeText(getApplicationContext(), R.string.please_login_warning,Toast.LENGTH_LONG).show();}
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
